

$(function() {
    
    toDataTable('dynamic-bordered');
    toDataTable('basic-table');
    toDataTable('dynamic-emphasis');
    toDataTable('dynamic-guideline');
    toDataTable('dynamic-condensed');
    toDataTable('dynamic-table');
    toDataTable('dynamic-controls');
    toDataTable('dynamic-crud');
    
    toDataTable('scroll-x');
    toDataTable('scroll-y');
    toDataTable('scroll-xy');
    
    toDataTable('text-filter');
    toDataTable('dropdown-filter');
    
    var id = 'text-filter';
    
//    $('#' +id+ ' tfoot th').each( function () {
//        var title = $('#' +id+ '  thead th').eq( $(this).index() ).text();
//        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
//    } );
// 
//    // DataTable
//    var table = $('#' +id).DataTable();
//     
//    // Apply the filter
//    $('#' +id+ ' tfoot input').on( 'keyup change', function () {
//        table
//            .column( $(this).parent().index()+':visible' )
//            .search( this.value )
//            .draw();
//    } );
    
    // search
    $('.dataTables_filter input').unwrap();
    $('.dataTables_filter input').attr("placeholder", "Search Term");
    $('.dataTables_filter input').addClass("form-control input-sm");
    $('.dataTables_filter input').wrap('<div class="input-group" />');
    $('.dataTables_filter input').parent().append('<span class="input-group-btn"><button type="submit" class="btn btn-default btn-sm"><i class="fa fa-search"></i></button></span>');
     
    // limit
    $('.dataTables_length select').addClass("form-control input-sm");
    
});


function toDataTable(id) {
    
    var table = $('#' + id);
    var tableOptions = {};
    
    tableOptions['oLanguage'] = {
        sSearch: '',
        sInfo: '<span>_START_</span> to <span>_END_</span> of <span>_TOTAL_</span>',
        sLengthMenu: '_MENU_',
//        sProcessing: '<img src="' +base_url + 'img/ajax-loader_dark.gif">',
        sEmptyTable: '<h3 class="text-center muted">No Records Available</h3>',
        sZeroRecords: '<h3 class="text-center muted">No Records Available</h3>'
    };
    
    if(table.hasClass('no-search')) {
        tableOptions['searching'] = false;
    } else {
        tableOptions['searching'] = true;
    }
    
    if(table.hasClass('no-sorting')) {
        tableOptions['ordering'] = false;
    } else {
        tableOptions['ordering'] = true;
    }
    
    if(table.hasClass('no-pagination')) {
        tableOptions['paging'] = false;
        tableOptions['oLanguage'] = {
            sInfo: ''
        };
    } else {
        tableOptions['paging'] = true;
        tableOptions['pagingType'] = 'full_numbers';
        //    tableOptions['sPaginationType'] = 'bootstrap';
        tableOptions['iDisplayStart'] = 0;
        tableOptions['aLengthMenu'] = [[10, 50, 100, -1], [10, 50, 100, 'All']];
        
    }
    
    if( table.hasClass('scroll-x') || table.hasClass('scroll-xy') ) {
        tableOptions['scrollX'] = true;
    }
    
    if( table.hasClass('scroll-y') || table.hasClass('scroll-xy') ) {
        tableOptions['scrollY'] = '200px';
        tableOptions['scrollCollapse'] = true;
    }
    
    if( table.hasClass('text-filter') ) {
        // add header filters
        var headFilters = $('<tr class="search-filters" />');
        $('#' +id+ ' thead th').each( function () {
            var title = $('#' +id+ ' thead th').eq( $(this).index() ).text();
            headFilters.append( '<th><input type="text" class="form-control" placeholder="Search '+title+'" /></th>' );
        } );
        $('#' +id+ ' thead').prepend(headFilters);
    }
    
    if( table.hasClass('dropdown-filter') ) {
        // add header filters
        var headFilters = $('<tr class="search-filters" />');
        $('#' +id+ ' thead th').each( function () {
            var title = $('#' +id+ ' thead th').eq( $(this).index() ).text();
            headFilters.append( '<th><input type="text" class="form-control" placeholder="Search '+title+'" /></th>' );
        } );
        $('#' +id+ ' thead').prepend(headFilters);
    }

    // Initialize DataTable
    var dataTable = table.DataTable(tableOptions);
     
    if( table.hasClass('text-filter') ) {
        // Apply the filter
        $('#' + id + ' thead input').on('keyup change', function() {
            dataTable
                    .column($(this).parent().index() + ':visible')
                    .search(this.value)
                    .draw();
        });
    }
    
    if( table.hasClass('dropdown-filter') ) {
        $('#' + id + ' tfoot th').each(function(i) {
            var select = $('<select class="form-control"><option value=""></option></select>')
                    .appendTo($(this).empty())
                    .on('change', function() {
                dataTable.column(i)
                        .search($(this).val())
                        .draw();
            });

            dataTable.column(i).data().unique().sort().each(function(d, j) {
                select.append('<option value="' + d + '">' + d + '</option>');
            });
        });
    }
    
    
}














function more() {
    
   
    var opt = {};
                
    opt.oLanguage = {
        sSearch: '<span>Search:</span> ',
        sInfo: 'Showing <span>_START_</span> to <span>_END_</span> of <span>_TOTAL_</span> entries',
        sLengthMenu: '<span>Show entries:</span> _MENU_',
        sProcessing: '<img src="' +base_url + 'img/ajax-loader_dark.gif">',
        sEmptyTable: '<h3 class="text-center muted">No Records Available</h3>'
    };
                
    opt.sPaginationType = 'full_numbers';
    opt.iDisplayLength = 10;
    opt.iDisplayStart = 0;
    opt.bAutoWidth = false;

    opt.aoColumns = aoColumns;
                
//                opt.aoColumnDefs = [{
//                    bSortable: !1,
//                    aTargets: [0,6]
//                }];
                
    opt.sDom = "lfrtip";

    opt.bProcessing = true;
    opt.bServerSide = true;
    opt.sAjaxSource = ajaxSource;
    opt.iDisplayLength = 10;
    opt.iDisplayStart = 0;
                
    opt.fnServerData = function(sSource, aoData, fnCallback) {
        $.ajax
        ({
            'dataType': 'json',
            'type': 'POST',
            'url': sSource,
            'data': aoData,
            'success': fnCallback
        });
    };
                
    opt.fnDrawCallback = function(oSettings) {
        make_rows_selectable();
        if ((typeof (use_modals) === 'undefined') || typeof (use_modals) === null) {
            if ((typeof (use_ajax) === 'undefined') || typeof (use_ajax) === null) {

            } else {
                add_ajax();
            }
        } else {
            add_modal(); 
        }
    };
                
    if(table.hasClass("dataTable-noheader")){
        opt.bFilter = false;
        opt.bLengthChange = false;
    }
    if(table.hasClass("dataTable-nofooter")){
        opt.bInfo = false;
        opt.bPaginate = false;
    }
    if(table.hasClass("dataTable-nosort")){
        var column = table.attr('data-nosort');
        column = column.split(',');
        for (var i = 0; i < column.length; i++) {
            column[i] = parseInt(column[i]);
        }
        opt.aoColumnDefs =  [{ 
            'bSortable': false, 
            'aTargets': column 
        }];
    }
    if(table.hasClass("dataTable-scroll-x")){
        opt.sScrollX = "100%";
        opt.bScrollCollapse = true;
        $(window).resize(function(){
            oTable.fnAdjustColumnSizing();
        });
    }
    if(table.hasClass("dataTable-scroll-y")){
        opt.sScrollY = "300px";
        opt.bPaginate = false;
        opt.bScrollCollapse = true;
        $(window).resize(function(){
            oTable.fnAdjustColumnSizing();
        });
    }
    if(table.hasClass("dataTable-reorder")){
        opt.sDom = "R"+opt.sDom;
    }
    if(table.hasClass("dataTable-colvis")){
        opt.sDom = "C"+opt.sDom;
        opt.oColVis = {
            "buttonText": "Change columns <i class='icon-angle-down'></i>"
        };
    }
    if(table.hasClass('dataTable-tools')){
        opt.sDom= "T"+opt.sDom;
        opt.oTableTools = {
            "sSwfPath": "js/plugins/datatable/swf/copy_csv_xls_pdf.swf"
        };
    }
    if(table.hasClass("dataTable-scroller")){
        opt.sScrollY = "300px";
        opt.bDeferRender = true;
        if(table.hasClass("dataTable-tools")){
            opt.sDom = 'TfrtiS';
        } else {
            opt.sDom = 'frtiS';
        }
    }
    if(table.hasClass("dataTable-grouping") && table.attr("data-grouping") == "expandable"){
        opt.bLengthChange = false;
        opt.bPaginate = false;
    }

    dataTable = table.dataTable(opt);
    table.css("width", '100%');
    $('.dataTables_filter input').attr("placeholder", "Search here...");
    
//                $(".dataTables_length select").wrap("<div class='input-mini'></div>").chosen({
//                    disable_search_threshold: 9999999
//                });

    $(".dataTables_length select").wrap("<div class='input-mini'></div>");

    $("#check_all").click(function(e){
        $('input', dataTable.fnGetNodes()).prop('checked',this.checked);
    });
    if(table.hasClass("dataTable-fixedcolumn")){
        new FixedColumns( dataTable );
    }
    if(table.hasClass("dataTable-columnfilter")){
        dataTable.columnFilter({
            "sPlaceHolder" : "head:after",
            sRangeFormat: "{from}{to}",
            aoColumns: filter
        });
    }
    if(table.hasClass("dataTable-grouping")){
        var rowOpt = {};

        if(table.attr("data-grouping") == 'expandable'){
            rowOpt.bExpandableGrouping = true;
        }
        dataTable.rowGrouping(rowOpt);
    }
}